package com.example.blog.controller;

import com.example.blog.Service.UserService;
import com.example.blog.entity.Article;
import com.example.blog.entity.User;
import com.example.blog.repository.ArticleRepository;
import com.example.blog.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;

import java.util.Optional;
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginCtl {
    @GetMapping
    public String Jump(){
        return "login";
    }
    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ArticleRepository articleRepository;
    //User user= userRepository.findByname(name);
    @GetMapping(value = "/goToBlog")
    public String goToBlog() {
        return "blog"; // 重定向到 /blog
    }

    @GetMapping(value = "/users")
    public String showUsersPage(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            List<Article> articles = articleRepository.findArticlesByUsername(user.getName());
            model.addAttribute("articles", articles); // 确保属性名是 "articles"
            return "users";
        } else {
            return "login";
        }
    }
    @GetMapping(value = "/publish")
    public String showUPub() {
        return  "articlePublish";
    }
    @PostMapping
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        RedirectAttributes redirectAttributes,
                        HttpSession session) {
        int result = userService.login(username, password);
        User user=userRepository.findByname(username);
        if (user != null && user.getPassword().equals(password)){
            session.setAttribute("user", user); // 确保这一行被执行
        }
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "登录成功！");
            return "blog";
        } else {
            redirectAttributes.addFlashAttribute("error", "登录失败，可能是账号不存在！");
            return "login";
        }
    }



}


